package com.gtx.common.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Maps;
import com.gtx.common.dao.AdminMapper;
import com.gtx.common.pojo.Admin;
import com.gtx.common.pojo.RespBean;
import com.gtx.common.config.security.JwtTokenUtil;
import com.gtx.common.service.IAdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * @author songyurui
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AdminMapper adminMapper;

    /**
     * 登录之后 返回token
     * @param userName  用户名
     * @param password  密码
     * @param request 请求
     * @return RespBean
     */

    @Override
    public RespBean login(String userName, String password, HttpServletRequest request) {

        // 登录
        UserDetails userDetails = userDetailsService.loadUserByUsername(userName);
        if (null == userDetails || passwordEncoder.matches(password, userDetails.getPassword())) {
           return RespBean.error("用户名或密码不正确");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号被禁用，请联系管理员！");
        }

        // 更新security 登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails, null, userDetails.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);

        // 登录成功，生成token令牌
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String,String> tokenMap = Maps.newHashMap();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        return RespBean.success("登录成功", tokenMap);
    }

    /**
     * 根据用户名获取有效用户
     * @param username 用户名
     * @return Admin
     */

    @Override
    public Admin getAdminByUserName(String username) {
        return adminMapper
                .selectOne(new QueryWrapper<Admin>().eq("userName", username).eq("enabled", true));
    }
}
